import { debounce } from '@/utils/helper';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import utils from '@/utils/index';
import { Input, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import GetOpenId from '@/components/GetOpenId/';
import { appid, appid_h5 } from '@/src/config';
import GiftCardBackground from '../giftCardBackground';
import './index.scss';
import { getPrePayBase, pay, PayStatus } from './pay';

const CardDenomination = ({ priceItem, selected }) => {
  const { sellingPrice, fixedPrice } = priceItem ?? {};

  return (
    <View
      className={classNames('card-denomination', {
        selected,
        customePageBorderStyle: selected,
        customeSalesPromotionLabelStyle: selected,
      })}
    >
      <View className="top">
        <View
          className={classNames('price', {
            customePageStyle: selected,
          })}
        >
          {sellingPrice}元
        </View>
      </View>
      <View className="bottom">
        <View
          className={classNames('recharge-price', {
            customePageStyle: selected,
          })}
        >
          到账 {fixedPrice}元
        </View>
      </View>
    </View>
  );
};

const getValidPrice = (v) => {
  const price = parseFloat(v);

  if (Number.isNaN(price)) {
    Taro.showToast({
      title: '充值面额需大于0',
      icon: 'none',
    });

    return undefined;
  }

  if (price <= 0) {
    Taro.showToast({
      title: '充值面额需大于0',
      icon: 'none',
    });
    return undefined;
  }

  if (price > Number.MAX_SAFE_INTEGER) {
    Taro.showToast({
      title: '充值面额错误',
      icon: 'none',
    });

    return undefined;
  }

  return price;
};

const GiftCardRecharge = ({ dispatch, loading, giftCardInfo, rechargeAmount }) => {
  useShowLoading(loading, ['giftCard/getGiftCardInfo', 'giftCard/getRechargeAmount']);

  const router = useRouter();
  const { params = {} } = router;

  const isShowCustom = rechargeAmount?.isCustom === 1;

  const [selected, setSelected] = useState({ index: -1, customPrice: undefined });

  const handleSelected = (customPrice, index) => {
    if (customPrice) {
      getValidPrice(customPrice);
      setSelected({ index: undefined, customPrice, selectedPrice: undefined });
      return;
    }

    const price = parseFloat(rechargeAmount?.rechargeAmount?.[index]?.sellingPrice ?? 0);
    setSelected({ index, customPrice: undefined, selectedPrice: price });
  };

  const goToStores = () => {
    Taro.navigateTo({ url: '/giftCardSubPack/giftCardStores/index?id=' + params.id });
  };

  const goToPay = useCallback(
    debounce(async () => {
      const price = getValidPrice(selected.customPrice ?? selected.selectedPrice);

      if (price === undefined) {
        return;
      }

      const u = '/giftCardSubPack/giftCardBuyResult/index';

      const { channel, openId } = getPrePayBase();

      const { orderId, payResult } = await dispatch({
        type: 'giftCard/payGiftCard',
        payload: {
          amount: price,
          cardId: params.id,
          wxOpenId: openId,
          wxAppId: Taro.$isH5 ? appid_h5 : appid,
          channel,
        },
      });
      const { status } = await pay(orderId, payResult);

      if (status === PayStatus.success) {
        Taro.redirectTo({ url: `${u}?price=${price}&success=1` });
      } else {
        Taro.redirectTo({ url: `${u}?price=${price}` });
      }
    }, 2000),
    [selected],
  );

  // 初始化选中
  useEffect(() => {
    if (!rechargeAmount) {
      return;
    }

    handleSelected(undefined, 0);
  }, [rechargeAmount]);

  useEffect(() => {
    if (!params.id) {
      Taro.navigateBack();
      return;
    }

    // 获取提货券详情
    dispatch({
      type: 'giftCard/getGiftCardInfo',
      payload: params.id,
    });

    // 获取提货券储值金额列表
    dispatch({
      type: 'giftCard/getRechargeAmount',
      payload: params.id,
    });
  }, [params.id]);

  return (
    <>
      <GetOpenId />

      <View className="giftCardRecharge">
        <View className="card-name">{giftCardInfo?.cardName}</View>

        <GiftCardBackground className="card-logo" {...giftCardInfo} />

        <View className="card-denomination-name">提货券面额</View>

        <View className="card-denomination-list">
          <View className="wrap">
            {rechargeAmount?.rechargeAmount?.map((priceItem, index) => {
              return (
                <View
                  key={priceItem.fixedPrice}
                  onClick={() => {
                    handleSelected(undefined, index);
                  }}
                >
                  <CardDenomination
                    priceItem={priceItem}
                    selected={selected?.index === index}
                  ></CardDenomination>
                </View>
              );
            })}
          </View>
        </View>

        {isShowCustom && (
          <View className="card-denomination-custom-wrap">
            <View className="card-denomination-custom">
              <View className="denomination-prefix">自定义面额</View>
              <View className="denomination-unit">¥</View>
              <Input
                className="denomination-input"
                placeholderClass="denomination-input-placeholder"
                type="number"
                placeholder="输入充值面额"
                value={selected.customPrice}
                onInput={(e) => {
                  let v = e?.detail?.value;

                  handleSelected(v);
                }}
              />
            </View>
          </View>
        )}

        <View className="card-instruction">
          <View className="title">提货券使用须知</View>

          <View className="applicable-store">
            <View className="left">适用门店：</View>
            <View className="right customePageStyle" onClick={goToStores}>
              查看可用门店
            </View>
          </View>

          <View className="applicable-notice">
            <View className="left">适用须知：</View>
            <View className="right">{giftCardInfo?.explain}</View>
          </View>
        </View>

        <View
          className="go-to-buy"
          style={{
            height: `${utils.getSizeByScale(126) + Taro.$bottomHight}px`,
          }}
        >
          <View className="wrap">
            <View className="left">
              <View className="title">应支付：</View>
              <View className="price">¥{selected.customPrice ?? selected.selectedPrice}</View>
            </View>

            <View className="right customePageBackgroundStyle" onClick={goToPay}>
              <View className="button-text">去支付</View>
            </View>
          </View>
        </View>
      </View>
    </>
  );
};
export default connect(({ loading, giftCard }) => ({
  loading,

  giftCardInfo: giftCard.giftCardInfo,
  rechargeAmount: giftCard.rechargeAmount,
}))(GiftCardRecharge);
